package it.apiconsulting.wot.controller;


import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.classic.Session;

import it.apiconsulting.wot.model.Logged;
import it.apiconsulting.wot.util.HibernateUtil;


public class LoggedManager extends HibernateUtil {
	
	public Logged add(Logged logged) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		session.save(logged);
		session.getTransaction().commit();
		return logged;
	}
	
	public Logged delete(Long id) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		Logged logged = (Logged) session.load(Logged.class, id);
		if(null != logged) {
			session.delete(logged);
		}
		session.getTransaction().commit();
		return logged;
	}
	
	public void deleteByIdUtente(Long idUtente) {
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		Query query = session.createQuery("DELETE Logged WHERE id_utente = "+idUtente);
		query.executeUpdate();
		session.getTransaction().commit();		
	}
	
	public Logged getUtenteByIdUtente(Long idUtente) {
		
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		Logged logged = null;
		try {
			
			Query query = session.createQuery("from Logged where id_utente="+idUtente);
			logged = (Logged)query.uniqueResult();
			
		} catch (HibernateException e) {
			e.printStackTrace();
			session.getTransaction().rollback();
		}
		session.getTransaction().commit();
		return logged;
	}
	
	public Logged isUtenteActive(Long idUtente) {
		
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		Logged logged = null;
		try{
			
			Query query = session.createQuery("FROM Logged WHERE id_utente="+idUtente+" AND now() BETWEEN login_date AND logout_date");
			logged = (Logged)query.uniqueResult();
		} catch (HibernateException e) {
			e.printStackTrace();
			session.getTransaction().rollback();
		}
		session.getTransaction().commit();
		return logged;
	}

	public List<Logged> list() {
		
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.beginTransaction();
		List<Logged> loggeds = null;
		try {
			
			Query query = session.createQuery("from Logged");
			loggeds = (List<Logged>)query.list();
			
		} catch (HibernateException e) {
			e.printStackTrace();
			session.getTransaction().rollback();
		}
		session.getTransaction().commit();
		return loggeds;
	}
}
